package com.ydlclass.serialize.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.ydlclass.exceptions.SerializeException;
import com.ydlclass.serialize.AbstractSerialize;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Hessian序列化
 * @Author duWenJian
 * @Date 2024/2/23 16:37
 * @Version 1.0
 */
@Slf4j
public class HessianSerialize extends AbstractSerialize {
    @Override
    public byte[] serialize(Object obj) {
        if (obj == null){
            return null;
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            Hessian2Output hessian = new Hessian2Output(baos);
            hessian.writeObject(obj);
            hessian.flush();
            if (log.isDebugEnabled()) {
                log.debug("对象:{}完成了序列化序列化后的body为:{}",obj.getClass(),baos.toString());
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("序列化失败", e);
            throw new SerializeException("Hessian序列化失败,原因是:"+e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<?> clazz) {
        if (bytes == null || clazz == null){
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);) {
            Hessian2Input hessian = new Hessian2Input(bais);
            return  (T)hessian.readObject();
        } catch (IOException e) {
            log.error("反序列化失败", e);
            throw new SerializeException("Hessian反序列化失败,原因是:"+e);
        }
    }
}
